<?php

namespace common\modules\wechat\controllers\frontend\process;

use common\modules\wechat\models\frontend\Account;
use common\modules\wechat\models\frontend\Fans;
use common\modules\wechat\components\ProcessController;
use Yii;

/**
 * 微信粉丝请求默认处理
 *
 * @package common\modules\wechat\controllers\frontend
 */
class FansController extends ProcessController
{

    /**
     * 数据记录
     *
     * @return array
     * @throws \yii\base\InvalidConfigException
     */
    public function actionRecord()
    {
        $wechat = $this->getWechat();
        $fans = $this->getFans();
        if ( ! $fans)
        {
            Yii::trace('存储粉丝信息', __METHOD__);
            /** @var Fans $fans */
            $fans = new Fans;
            $fans->setAttributes([
                'wid'     => $wechat->id,
                'open_id' => $this->message['FromUserName'],
                'status'  => Fans::STATUS_SUBSCRIBED,
            ]);
            if ($fans->save())
            {
                if ($wechat->status > Account::TYPE_SUBSCRIBE)
                {
                    Yii::trace('更新用户详细数据, 普通订阅号无权限获取', __METHOD__);
                    $fans->updateUser();
                }
            }
            else
            {
                Yii::warning('保存粉丝信息时出错:' . $fans->formatErrors(), __METHOD__);
            }
        }
        elseif ($fans->status != Fans::STATUS_SUBSCRIBED)
        {
            Yii::trace('更新关注状态');
            $fans->subscribe();
        }
    }

    /**
     * 关注处理
     */
    public function actionSubscribe()
    {
    }

    /**
     * 取消关注处理
     */
    public function actionUnsubscribe()
    {
        if ($fans = $this->getFans())
        {
            $fans->unsubscribe();
        }
    }
}
